<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd()"
          >新增
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-if="refreshTable" v-loading="loading" :data="toolList">
      <el-table-column prop="goodsName" label="商品名称" />
      <el-table-column prop="categoryName" label="商品分类" align="center">
        <template v-slot="scope">
          <el-tag class="mr5" v-for="tag in scope.row.categoryName">{{
            tag
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="createTime">
        <template v-slot="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="scope.row.postUrl"
            :preview-src-list="[scope.row.postUrl]"
            fit="cover"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="goodsPrice" label="商品价格(元)" align="center" />
      <el-table-column prop="orderNum" label="排序" align="center" />
      <el-table-column label="状态" align="center" key="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.num"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-tabs tab-position="left" v-if="open">
        <el-tab-pane label="基础信息">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="商品名称" prop="goodsName">
                  <el-input
                    v-model="form.goodsName"
                    placeholder="请输入商品名称"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品分类" prop="categoryId">
                  <treeselect
                    class="tree-select"
                    v-model="form.categoryId"
                    :options="toolOptions"
                    :normalizer="normalizer"
                    :multiple="true"
                    placeholder="选择父级类型"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品卖点" prop="goodsSellPoint">
                  <el-input
                    type="textarea"
                    :rows="2"
                    placeholder="请输入内容"
                    v-model="form.goodsSellPoint"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品标签" prop="goodsTags">
                  <el-tag
                    class="my-tag"
                    :key="tag"
                    v-for="tag in form.goodsTags"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="inputVisible"
                    v-model="inputValue"
                    ref="saveTagInput"
                    @keyup.enter.native="handleInputConfirm"
                    @blur="handleInputConfirm"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" @click="showInput"
                    >+ 新标签</el-button
                  >
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品属性" prop="goodsAttributes">
                  <el-button type="text" @click="showAttr = true"
                    >管理属性库</el-button
                  >

                  <div
                    class="attr-item"
                    v-for="(item, index) in form.attributeList"
                  >
                    <i
                      @click="handleDel(item, index)"
                      class="el-icon-delete"
                    ></i>
                    <div class="mb10">
                      <span class="label"> 属性名称：</span>
                      <el-select
                        v-model="item.attributeId"
                        style="width: 100%"
                        @change="changeAttr(item)"
                      >
                        <el-option
                          v-for="option in attributeList"
                          :label="option.attributeName"
                          :value="option.attributeId"
                          :key="option.attributeId"
                          :disabled="option.disabled"
                        ></el-option>
                      </el-select>
                    </div>
                    <div>
                      <span class="label"> 属性值：</span>
                      <el-select
                        v-model="item.optionIds"
                        multiple
                        style="width: 100%"
                      >
                        <el-option
                          v-for="option in item.attributeOptions"
                          :label="option.optionKey"
                          :value="option.optionId"
                          :key="option.optionId"
                        ></el-option>
                      </el-select>
                    </div>
                  </div>
                  <div class="attrbutes-wrap">
                    <el-button
                      @click="handleAddAttr"
                      type="text"
                      icon="el-icon-plus"
                      >添加属性</el-button
                    >
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品价格" prop="goods_price">
                  <el-input-number
                    v-model="form.goodsPrice"
                    :precision="2"
                    :step="0.1"
                  ></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品库存" prop="goods_stock">
                  <el-input-number
                    v-model="form.goodsStock"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品图片" prop="postUrl">
                  <imageUpload :value.sync="form.postUrl" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="排序" prop="orderNum">
                  <el-input-number
                    v-model="form.orderNum"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态">
                  <el-radio-group v-model="form.status">
                    <el-radio
                      v-for="dict in statusOptions"
                      :key="dict.value"
                      :label="dict.value"
                      >{{ dict.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="商品介绍">
          <Tinymce v-if="open" v-model="form.goodsDetail" :height="600" />
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 属性库 -->
    <AttributeList :showDialog.sync="showAttr" />
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  getGoodsList,
  goodsAdd,
  goodsEdit,
  goodsDel,
  goodsGet,
} from "@/api/goods/goods";
import { getCategoryTree } from "@/api/goods/category";
import ImageUpload from "@/components/ImageUpload/index.vue";
import Tinymce from "@/components/tinymce/index.vue";
import AttributeList from "./components/AttributeList.vue";
export default {
  name: "SystemDept",
  components: { ImageUpload, Treeselect, Tinymce, AttributeList },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      toolList: [],
      // 类型树选项
      toolOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 是否展开
      expand: false,
      // 查询参数
      queryParams: {
        goodsName: undefined,
        status: undefined,
        num: 10,
        page: 1,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
        ],
        categoryId: [
          { required: true, message: "商品类型不能为空", trigger: "blur" },
        ],
        orderNum: [
          { required: true, message: "显示排序不能为空", trigger: "blur" },
        ],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
        postUrl: [
          { required: true, message: "商品图片不能为空", trigger: "blur" },
        ],
      },
      // 总条数
      total: 0,
      // 数据字典
      statusOptions: [
        { value: 1, label: "上架" },
        { value: 0, label: "下架" },
      ],
      inputVisible: false,
      inputValue: "",
      showAttr: false,
    };
  },
  created() {
    this.getList();
  },
  computed: {
    attributeList() {
      return this.$store.state.user.attributeList;
    },
  },
  methods: {
    /** 查询类型列表 */
    getList() {
      this.loading = true;
      getGoodsList(this.queryParams).then((response) => {
        this.toolList = response.data;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 转换类型数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        categoryId: [],
        goodsTags: [],
        goodsName: "",
        orderNum: "",
        status: 1,
        postUrl: "",
        goodsStock: 0,
        goodsPrice: 0,
        goodsDetail: "",
        attributeList: [],
      };
      this.attributeList.map((a) => {
        this.$set(a, "disabled", false);
      });
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
      getCategoryTree().then((response) => {
        // 处理 toolOptions 参数
        this.toolOptions = response.data;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      goodsGet(row.goodsId).then((res) => {
        this.form = res.data;
        if (this.form.parentId === 0) {
          // 无父类型时，标记为 undefined，避免展示为 Unknown
          this.form.parentId = "";
        }
        this.form.categoryId = this.form.categoryId.split(",");
        if (!this.form.goodsTags) {
          this.form.goodsTags = [];
        }
        if (this.form.attributeList.length) {
          this.form.attributeList.map((a) => {
            this.changeAttr(a);
          });
        }
        this.open = true;
        this.title = "修改商品";
        getCategoryTree().then((response) => {
          this.toolOptions = response.data;
        });
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      console.log(this.form);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.form));
          params.categoryId = params.categoryId.join(",");
          params.goodsTags = params.goodsTags.join(",");
          let flag = false;
          if (params.attributeList.length) {
            params.attributeList.map((a) => {
              if (a.optionIds.length === 0 || !a.attributeId) {
                flag = true;
              }
              a.optionIds = a.optionIds.join(",");
            });
          }
          if (flag) {
            this.$modal.msgError("请完善商品属性");
            return;
          }
          if (params.goodsId) {
            goodsEdit(params).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            goodsAdd(params).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除名称为"' + row.goodsName + '"的数据项?')
        .then(function () {
          return goodsDel(row.goodsId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 标签
    handleClose(tag) {
      this.form.goodsTags.splice(this.form.goodsTags.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.form.goodsTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },

    // 属性
    handleAddAttr() {
      this.form.attributeList.push({ attributeName: "", attributeOptions: [] });
    },
    changeAttr(item) {
      if (item.attributeId) {
        this.$set(item, "disabled", false);
        const result = this.attributeList.filter(
          (a) => a.attributeId === item.attributeId
        )[0];
        this.$set(result, "disabled", true);
        this.$set(item, "attributeOptions", result["values"]);
      } else {
        this.$set(item, "attributeOptions", []);
      }
    },
    handleDel(item, index) {
      const result = this.attributeList.filter(
        (a) => a.attributeId === item.attributeId
      )[0];
      this.$set(result, "disabled", false);
      this.form.attributeList.splice(index, 1);
    },
  },
};
</script>

<style lang="scss" scoped>
.tree-select {
  ::v-deep .vue-treeselect__multi-value-item {
    line-height: 24px;
  }
  ::v-deep .vue-treeselect__multi-value {
    margin-bottom: 0;
  }
}
.mr5 {
  margin-right: 5px;
}
.my-tag {
  margin-right: 10px;
}
.button-new-tag {
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  vertical-align: bottom;
}
.attrbutes-wrap {
  text-align: center;
  border-radius: 5px;
  background: #f7f7f7;
}

.attr-item {
  position: relative;
  padding: 10px 55px 10px 10px;
  border: 1px solid #dedede;
  border-radius: 5px;
  margin-bottom: 10px;
  > div {
    display: flex;
  }
  .label {
    width: 100px;
  }
  .el-icon-delete {
    position: absolute;
    right: 10px;
    top: 38px;
    font-size: 20px;
    cursor: pointer;
    color: #bbb;
    border: 1px solid #dedede;
    padding: 5px;
    border-radius: 4px;
  }
}
</style>
